package com.dabai.simpleconnection_udp.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dabai.simpleconnection_udp.R;
import com.dabai.simpleconnection_udp.base.BaseAlertDialogBuilder;
import com.dabai.simpleconnection_udp.bean.UdpCommandModel;
import com.dabai.simpleconnection_udp.db.SQLiteDatabaseHelper;
import com.dabai.simpleconnection_udp.log.LogTagEnum;
import com.dabai.simpleconnection_udp.log.LogUtils;
import com.dabai.simpleconnection_udp.utils.DabaiUtils;
import com.dabai.simpleconnection_udp.utils.FileUtils;
import com.dabai.simpleconnection_udp.utils.MdcDialog;
import com.dabai.simpleconnection_udp.utils.NotificationUtils;
import com.dabai.simpleconnection_udp.utils.ViewUtils;

import java.nio.charset.Charset;

import es.dmoral.toasty.Toasty;

public class SettingsActivity extends AppCompatActivity {

    static SQLiteDatabase db;
    @SuppressLint("StaticFieldLeak")
    static Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        initDB();
        activity = this;

    }

    /**
     * 初始化数据库
     */
    private void initDB() {
        //todo 初始化数据库
        db = openOrCreateDatabase("UDPSet", Context.MODE_PRIVATE, null);
        String create = "create table if not exists UDPSet(id integer primary key autoincrement,name text not null,note text not null,ip text not null,port integer not null,content text not null);";
        db.execSQL(create);

        String create2 = "create table if not exists UDPRecv(id integer primary key autoincrement,name text not null,note text not null,port integer not null UNIQUE,last text not null);";
        db.execSQL(create2);
    }

    public static void backupAllDia(Context context) {

        //todo 备份

        JSONArray jsonArray = new JSONArray();

        String search = "select * from UDPSet";
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery(search, null);

        while (cursor.moveToNext()) {
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") String content = cursor.getString(cursor.getColumnIndex("content"));
            @SuppressLint("Range") String ip = cursor.getString(cursor.getColumnIndex("ip"));
            @SuppressLint("Range") int port = cursor.getInt(cursor.getColumnIndex("port"));
            @SuppressLint("Range") String note = cursor.getString(cursor.getColumnIndex("note"));

            jsonArray.add(JSONObject.toJSON(new UdpCommandModel(id, name, note, ip, port, content)));

        }

        if (jsonArray.size() == 0){
            Toasty.info(context, "无数据", Toast.LENGTH_SHORT, true).show();
            return;
        }

        MdcDialog.showConfirmDialog(context, "备份", jsonArray.toJSONString(), "复制", new MdcDialog.OnConfirmDialogButtonListener() {
            @Override
            public void confirm() {
                ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

                ClipData.Item item = new ClipData.Item(jsonArray.toJSONString());
                ClipData clipData = new ClipData("text", new String[]{"text/plain"}, item);

                clipboard.setPrimaryClip(clipData);
                Toasty.success(context, "复制成功", Toast.LENGTH_SHORT, true).show();
                LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "备份数据", jsonArray.size());

            }

            @Override
            public void cancel() {

            }
        }).show();

    }


    public static void importAllDia(Activity context) {
        //todo 恢复
        MdcDialog.showInputDialog(context, "导入", "", "请输入JSON文本", "导入", new MdcDialog.OnInputDialogButtonListener() {
            @Override
            public void confirm(AlertDialog dialog, String content) {

                JSONArray jsonArray = JSONArray.parseArray(content);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    UdpCommandModel udpCommandModel2 = new UdpCommandModel(jsonObject.getString("name"),
                            jsonObject.getString("note"), jsonObject.getString("ip"), jsonObject.getIntValue("port"), jsonObject.getString("content"));

                    long id = SQLiteDatabaseHelper.insertData(db, udpCommandModel2);

                }

                dialog.dismiss();

                Toasty.success(context, "导入成功", Toast.LENGTH_SHORT, true).show();
                LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "导入数据", jsonArray.size());

                Intent resultIntent = new Intent();
                resultIntent.putExtra("isRef", true); // 设置返回的数据，可以使用putExtra()方法传递数据
                context.setResult(101, resultIntent); // 设置返回码和返回结果
                activity.finish();
            }

            @Override
            public void cancel() {

            }
        }).show();

    }

    public static void delAllDia(Activity context) {

        MdcDialog.showConfirmDialog(context, "删除全部", "确定删除全部命令嘛", "确认", new MdcDialog.OnConfirmDialogButtonListener() {
            @Override
            public void confirm() {
                SQLiteDatabaseHelper.deleteTable(db, "UDPSet");

                Toasty.success(context, "删除成功", Toast.LENGTH_SHORT, true).show();
                LogUtils.appendLog(LogTagEnum.TAG_TAG_OTHER, "清空数据库");

                activity.finishAffinity();
            }

            @Override
            public void cancel() {

            }
        }).show();

    }

    @SuppressLint("CheckResult")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void initNot(Activity context) {
        if (!NotificationUtils.isNotificationEnabled(context)) {

            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);

            Toasty.info(context, "请授予通知栏权限", Toast.LENGTH_SHORT, true);

        }
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {


        Context context;
        private SwitchPreferenceCompat notSwitch;

        @Override
        public void onResume() {

            if (!NotificationUtils.isNotificationEnabled(context)){
                notSwitch.setChecked(false);
            }
            super.onResume();
        }

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            context = getContext();

            notSwitch = findPreference("not");
            SwitchPreferenceCompat utfSwitch = findPreference("utf");


            if (notSwitch != null) {
                notSwitch.setOnPreferenceChangeListener((preference, newValue) -> {
                    // 处理开关状态改变的逻辑
                    boolean isChecked = (boolean) newValue;

                    if (isChecked){
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //Android O以下不用开启权限
                            initNot(activity);
                        }
                    }
                    // 返回true表示允许改变开关状态，返回false表示禁止改变开关状态
                    return true;
                });
            }

            Charset defaultCharset = Charset.defaultCharset();
            if (utfSwitch != null) {
                utfSwitch.setSummary("本设备默认编码: " + defaultCharset.displayName());
            }

        }


        @Override
        public boolean onPreferenceTreeClick(Preference preference) {
            switch (preference.getKey()) {
                case "backupAll" -> backupAllDia(context);
                case "importAll" -> importAllDia(activity);
                case "delAll" -> delAllDia(activity);
                case "dev" -> startDevUi();
                case "log" -> startLogUi();
                case "coolapk" -> openCool(activity);
                default -> {
                }
            }
            return super.onPreferenceTreeClick(preference);
        }

        private void openCool(Activity activity) {
            DabaiUtils.openLink(context,"https://www.coolapk.com/apk/"+activity.getPackageName());
        }

        /**
         * 启动日志ui
         */
        private void startLogUi() {
            View diaView = ViewUtils.inflateLayout(context, R.layout.dialog_log);
            TextView textView1 = diaView.findViewById(R.id.appLogTextView);

            String text = FileUtils.readText(LogUtils.getPath());
            textView1.setText(text);

            ScrollView scrollView = diaView.findViewById(R.id.logScroll);

            new BaseAlertDialogBuilder(context)
                    .setTitle("app log - " + FileUtils.getFileSizeToString(LogUtils.getFile()))
                    .setView(diaView)
                    .setPositiveButton("确认", null)
                    .setNeutralButton("清空", (dialog, which) -> {
                        FileUtils.delete(LogUtils.getPath());
                    }).show();
            // 将ScrollView滚动到底部
            scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN));
        }

        /**
         * 启动dev-ui
         */
        private void startDevUi() {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
            startActivity(intent);
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        if (item.getItemId() == android.R.id.home) {// 处理返回逻辑
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}